package cc.mrbird.febs.buss.controller;

import cc.mrbird.febs.buss.entity.Halldepart;
import cc.mrbird.febs.buss.entity.TFile;
import cc.mrbird.febs.buss.service.IHalldepartService;
import cc.mrbird.febs.common.annotation.ControllerEndpoint;
import cc.mrbird.febs.common.utils.FebsUtil;
import cc.mrbird.febs.common.entity.FebsConstant;
import cc.mrbird.febs.common.controller.BaseController;
import cc.mrbird.febs.common.entity.FebsResponse;
import cc.mrbird.febs.common.entity.QueryRequest;
import cc.mrbird.febs.buss.entity.Item;
import cc.mrbird.febs.buss.service.IItemService;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.*;
import javax.validation.Valid;
import javax.validation.constraints.NotBlank;

/**
 *  Controller
 *
 * @author Lujingyuan
 * @date 2021-10-07 19:22:09
 */
@Slf4j
@Validated
@Controller
public class ItemController extends BaseController {

    @Autowired
    private IItemService itemService;
    @Autowired
    private IHalldepartService halldepartService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "item")
    public String itemIndex(){
        return FebsUtil.view("item/item");
    }

    @GetMapping("item")
    @ResponseBody
    @RequiresPermissions("item:list")
    public FebsResponse getAllItems(Item item) {
        return new FebsResponse().success().data(itemService.findItems(item));
    }

    @GetMapping("item/list")
    @ResponseBody
    public FebsResponse itemList(QueryRequest request, HttpServletRequest req, Item item) {
        Enumeration enu=req.getParameterNames();
        HashMap<String,String> map=new HashMap<String,String>();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            map.put(paraName,req.getParameter(paraName));
        }
        Map<String, Object> dataTable = getDataTable(this.itemService.findItemDetail(request, map));
        return new FebsResponse().success().data(dataTable);
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "item/add")
    public String goItemAdd() {
        return FebsUtil.view("item/itemAdd");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "item/update/{id}")
    public String goItemUpdate(@PathVariable String id, Model model) {
        Item obj= itemService.getById(id);
        model.addAttribute("obj",obj);
        return FebsUtil.view("item/itemUpdate");
    }

    @ControllerEndpoint(operation = "新增Item", exceptionMessage = "新增Item失败")
    @PostMapping("item")
    @ResponseBody
    public FebsResponse addItem(@Valid Item item) {
        Halldepart dept=halldepartService.getById(item.getDeptId());
        if(dept!=null){
            item.setDeptName(dept.getDeptName());
        }
        this.itemService.add(item);
        return new FebsResponse().success();
    }

    @GetMapping("item/delete/{objIds}")
    @ControllerEndpoint(operation = "删除", exceptionMessage = "删除失败")
    @ResponseBody
    public FebsResponse deleteItem( @PathVariable String objIds) {
        String[] ids = objIds.split(StringPool.COMMA);
        this.itemService.deleteItem(ids);
        return new FebsResponse().success();
    }

    @ControllerEndpoint(operation = "修改Item", exceptionMessage = "修改Item失败")
    @PostMapping("item/update")
    @ResponseBody
    public FebsResponse updateItem(Item item) {
        Halldepart dept=halldepartService.getById(item.getDeptId());
        if(dept!=null){
            item.setDeptName(dept.getDeptName());
        }
        this.itemService.updateItem(item);
        return new FebsResponse().success();
    }

    @PostMapping(value = "item/fileUpload")
    @ResponseBody
    public void fileUpload(@RequestParam(value = "file") MultipartFile file, Model model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        StringBuffer sb=new StringBuffer();
        String msg="上传成功";
        String src="http://localhost/tFile/preFile/";
        Integer code=0;
        if (file.isEmpty()) {
            System.out.println("文件为空");
            code=1;
            msg="上传失败";
        }
        String fileName = file.getOriginalFilename();  // 文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));  // 后缀名
        String filePath = "D://queue_file//"; // 上传后的路径
        fileName = UUID.randomUUID() + suffixName; // 新文件名
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            FileInputStream fileInputStream=new FileInputStream(filePath + fileName);
            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(fileInputStream);
            int sheetNum = xssfWorkbook.getNumberOfSheets();
            System.out.println("该excel文件中总共有："+sheetNum+"个sheet");
            //遍历工作簿中的所有数据
            for(int i = 0;i<1;i++) {
                //读取第i个工作表
                System.out.println("读取第"+(i+1)+"个sheet");
                XSSFSheet sheet = xssfWorkbook.getSheetAt(i);
                //获取最后一行的num，即总行数。此处从0开始
                int maxRow = sheet.getLastRowNum();
               // for (int row = 0; row <1; row++) {
                for (int row = 1; row <= maxRow; row++) {
                    //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
                    int maxRol = sheet.getRow(row).getLastCellNum();
                    XSSFRow r=sheet.getRow(row);
                    System.out.println("--------第" + row + "行的数据如下--------");
                    String deptName=r.getCell(11)+"";
                    Map<String,Object> map=new HashMap<>();
                    map.put("deptName",deptName);
                    List<Halldepart> deptList=halldepartService.selectByMap(map);
                    Halldepart dept;
                    if(deptList==null||deptList.size()==0){
                        dept=new Halldepart();
                        dept.setDeptName(deptName);
                        dept.setIsRcfw("0");
                        dept.setIsQyfw("0");
                        dept.setIsGgfw("0");
                        dept.setIsYwtb("0");
                        dept.setIsXmfw("0");
                        halldepartService.add(dept);
                    }else{
                        dept=deptList.get(0);
                    }
                    Item item=new Item();
                    item.setName(r.getCell(0)+"");
                    item.setDeptId(dept.getId());
                    item.setDeptName(dept.getDeptName());
                    item.setBjlx(r.getCell(14)+"");
                    item.setFdqx(r.getCell(15)+"");
                    item.setFdqxsm(r.getCell(16)+"");
                    item.setCnsx(r.getCell(18)+"");
                    item.setCnsxsm(r.getCell(19)+"");
                    item.setZzsqclsqfs(r.getCell(21)+"");
                    item.setSfsf(r.getCell(29)+"");
                    item.setBljghqfs(r.getCell(40)+"");
                    item.setBjjgsm(r.getCell(43)+"");
                    item.setBgsj(r.getCell(62)+"");
                    item.setLxdh(r.getCell(64)+"");
                    item.setJdts(r.getCell(65)+"");
                    item.setIsRcfw("0");
                    item.setIsQyfw("0");
                    item.setIsGgfw("0");
                    item.setIsYwtb("0");
                    item.setIsXmfw("0");
                    itemService.add(item);

                    /*for (int rol = 0; rol < maxRol; rol++){
                        System.out.println(rol+"-"+sheet.getRow(row).getCell(rol) + "  ");
                    }
                    System.out.println();*/
                }
            }

        } catch (IOException e) {
            e.printStackTrace();

        }
        sb.append("{");

        sb.append("\"code\":"+code);

        sb.append("}");
        response.getWriter().write(sb.toString());
    }
}
